# 配网组件

import zz_code
import zz_mqtt
import zz_wifi
from zz_ble import ZZ_BLE


def of():
    return ZZ_MATCH_NETWORK()


class ZZ_MATCH_NETWORK():
    def __init__(self):
        self.success_callback = None
        self.wifi = zz_wifi.of()
        self.ble = ZZ_BLE(name="ESP32")

    # 配网成功回调
    def bind_success_callback(self, func):
        self.success_callback = func

    # 开始配网
    def begin(self):
        self.ble.bind_callabck(self.ble_msg_callback)
        self.ble.init()

    # 蓝牙接收处理
    def ble_msg_callback(self, msg):
        r = zz_code.json_to_return(msg)
        if r.err():
            self.ble.send_msg(r.to_json())
            return

        action = r.get_data("action")
        if action == 'wifi':  # 连接wifi
            self.wifi_action(r)
        if action == 'mqtt':  # 设备连接mqtt
            self.mqtt_action(r)

    def mqtt_action(self, r: zz_code.Return):
        device_key = r.get_data("device_key")
        if zz_code.str_is_empty(device_key):
            self.ble.send_msg(zz_code.of_return_action('mqtt', 2037, "缺少设备KEY"))
            return

        mqtt_host = r.get_data("mqtt_host")
        mqtt_topic = r.get_data("mqtt_topic", "siyoumi")
        zz_mqtt.set_info(mqtt_host, mqtt_topic, device_key)

        mqtt = zz_mqtt.of()
        mqtt.service_open()
        mqtt_ok = mqtt.connect()
        mqtt.service_close()
        if mqtt_ok:
            try:
                self.ble.send_msg(zz_code.of_return_action('mqtt', 0, "配网成功"))
                self.ble.service_close()
                #
                if self.success_callback is not None:
                    self.success_callback(r)
            except Exception as e:
                print(e)
        else:
            self.ble.send_msg(zz_code.of_return_action('mqtt', 5160, "配网失败"))
            self.ble.connect_led()
        pass

    def wifi_action(self, r: zz_code.Return):
        wifi_ssid = r.get_data("wifi_ssid")
        wifi_pwd = r.get_data("wifi_pwd")
        if zz_code.str_is_empty(wifi_ssid):
            self.ble.send_msg(zz_code.of_return_action('wifi', 2037, "缺少WiFi SSID"))
            return
        if zz_code.str_is_empty(wifi_pwd):
            self.ble.send_msg(zz_code.of_return_action('wifi', 2037, "缺少WiFi密码"))

        # 记录wifi密码
        zz_wifi.set_info(wifi_ssid, wifi_pwd)
        self.wifi.service_open()

        wifi_ok = self.wifi.begin_connect()
        print(f"ble_handle: {wifi_ok}")
        if wifi_ok:
            try:
                self.ble.send_msg(zz_code.of_return_action('wifi', 0, "WiFi连接成功"))
                # self.ble.service_close()
                #
                if self.success_callback is not None:
                    self.success_callback(r)
            except Exception as e:
                print(e)
        else:
            self.ble.send_msg(zz_code.of_return_action('wifi', 5060, "WiFi连接失败"))
            self.ble.connected()
